package com.cy.lib.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author CY
 * @title
 * @date 2015/7/13
 * @qq 568305883
 * @email tmxdyf@163.com
 */
public abstract class RecyclerAdapter<T> extends RecyclerView.Adapter {

    private Context mContext;
    private final List<T> mListData;
    protected LayoutInflater mInflater;


    public RecyclerAdapter(Context context) {
        mContext = context;
        mListData = new ArrayList<>();
        mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public abstract RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i);

    @Override
    public abstract void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i);

    @Override
    public int getItemCount() {
        return mListData.size();
    }

    public void addData(T t, boolean isNotify) {
        mListData.add(t);
        if (isNotify)
            notifyDataSetChanged();
    }

    public void addData(T t, boolean isNotify, int position) {
        mListData.add(position, t);
        if (isNotify)
            notifyDataSetChanged();
    }

    public void addData(T t) {
        addData(t, true);
    }

    public void addData(T t, int position) {
        addData(t, true, position);
    }

    public void addData(Collection<T> t) {
        mListData.addAll(t);
        notifyDataSetChanged();
    }

    public void addData(Collection<T> t, int position) {
        mListData.addAll(position, t);
        notifyDataSetChanged();
    }

    public void setData(Collection<T> t) {
        mListData.clear();
        mListData.addAll(t);
        notifyDataSetChanged();
    }

    public void clearData() {
        mListData.clear();
        notifyDataSetChanged();
    }

    public List<T> getData() {
        return mListData;
    }

    public T getData(int position) {
        return getData().get(position);
    }

    /**
     * 适应RecyclerView的高度
     *
     * @param viewGroup
     * @param itemView
     * @param spanCount
     */
    public void fitRecyclerViewHeight(ViewGroup viewGroup, View itemView, int spanCount) {
        int size = getItemCount();
        int row = size;
        int span = spanCount;
        if (span != 0)
            row = size % span == 0 ? size / span : size / span + 1;

        itemView.measure(0, 0);
        viewGroup.getLayoutParams().height = itemView.getMeasuredHeight() * row;
    }

    public static abstract class RecyclerHolder<T> extends RecyclerView.ViewHolder {

        public RecyclerHolder(View itemView) {
            super(itemView);
        }

        public abstract void setData(int position, T t);
    }
}
